package lagou.mode3.mode4;

import java.io.*;
import java.util.Scanner;

public class ClientOutput extends Thread{
    private PrintStream ps;
    private BufferedOutputStream bo;

    @Override
    public void run(){
        String path;
        BufferedInputStream bi=null;
        File f1;
        while (true) {
            System.out.println("[1]发送消息     [2]发送文件");
            System.out.println("请输入序号选择您要执行的操作：");
            int in = ScannerClient.getScanner().nextInt();
            switch (in){
                case 1:
                    System.out.println("请输入消息内容：");
                    String str1 = ScannerClient.getScanner().next();
                    ps.println(str1);
                    break;
                case 2:
                    //发送一段话，用于服务器端判断即将接收一个文件
                    ps.println("即将发送文件，请注意接收");
                    System.out.println("请输入您要发送的文件路径：");
                    path=ScannerClient.getScanner().next();
                    f1=new File(path);
                    String name=f1.getName();
                    if(f1.exists()){
                        ps.println(name);
                        try {
                            bi=new BufferedInputStream(new FileInputStream(f1));
                            byte[] bArr=new byte[1024];
                            int res=0;
                            System.out.println("向服务器开始传输...");
                            while ((res=bi.read(bArr))!=-1){
                                bo.write(bArr,0,res);
                            }
                            System.out.println("向服务器传输完成！");
                            bi.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if(null !=bi) {
                                try {
                                    bi.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    else {
                        System.out.println("该文件不存在，请核对路径后再重新输入！");
                    }
                    break;
                default:
                    System.out.println("输入错误，请重新输入！");
            }

        }
    }

    public ClientOutput(PrintStream ps,BufferedOutputStream bo){
        this.ps=ps;
        this.bo=bo;
    }
}
